package com.masonluo.mlonlinejudge.controller;

import com.masonluo.mlonlinejudge.api.TestcaseService;
import com.masonluo.mlonlinejudge.model.dto.TestCaseUploadDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;


@RestController
public class FileController {

   @Autowired
    private TestcaseService testcaseService;
    /**
     * 上传文件
     *
     */
    @PostMapping("/file")
    public TestCaseUploadDto upload(@RequestParam(defaultValue = "", required = false) String prefix,
                                    @RequestParam("file") MultipartFile  file) throws IOException {
        System.out.println("收到MultipartFile文件");
        System.out.println("文件名字："+file.getOriginalFilename());
        return testcaseService.uploadTestCase(file);

    }

    /**
     * 下载测试用例
     * @param testCaseId 目录id
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/downloadAllAttachment")
    @ResponseBody
    public void downloadAllAttachment(@RequestParam("testCaseId") String testCaseId, HttpServletRequest request, HttpServletResponse response ) throws Exception {
        System.out.println("获取测试用例文件夹名："+testCaseId);
        testcaseService.downloadAllAttachment(testCaseId, request, response);
    }


    @RequestMapping(value = "/getUrlDownload",method = RequestMethod.GET)
    @ResponseBody
    public void getUrlDownload(HttpServletResponse response) {
        // TODO 修改测试用例压缩包的存放路径
        // String url = "/home/mlojDir/mlojHome/tmp/test.zip";
        String url = "/usr/local/mloj/test.zip";
//        String url = "D:\\home\\home\\test.zip";
        File file = new File(url);
        //判断文件是否存在如果不存在就进行异常处理
        if (!(file.exists() && file.canRead())) {
            System.out.println("文件不存在");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @DeleteMapping(value = "/{testCaseId}")
    @ResponseBody
    public void delete(@PathVariable String testCaseId) throws Exception {
        testcaseService.deleteTestCase(testCaseId);
    }


}
